package kinect.viewer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import kinect.storage.KinectStorageProtos.Sequence;
import kinect.storage.KinectStorageProtos.Frame;

/**
 *
 * @author samo
 */
public class SaveSequence extends javax.swing.JFrame {
    Viewer viewer;
    JFileChooser fc;
    File file;
    FileOutputStream output;

    /** Creates new form SaveSequence */
    private SaveSequence() {
        initComponents();

        setTitle("Save new sequence");
        setDefaultCloseOperation(javax.swing.JFrame.HIDE_ON_CLOSE);
    }
    
    public SaveSequence(Viewer viewer) {
        initComponents();
        
        setTitle("Save new sequence");
        setDefaultCloseOperation(javax.swing.JFrame.HIDE_ON_CLOSE);

        // Custom
        this.viewer = viewer;
        initCustomComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextFieldFileName = new javax.swing.JTextField();
        jLabelFileName = new javax.swing.JLabel();
        jLabelFolderName = new javax.swing.JLabel();
        jTextFieldFolderName = new javax.swing.JTextField();
        jPanelButton = new javax.swing.JPanel();
        jButtonSave = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextFieldFileName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldFileNameActionPerformed(evt);
            }
        });

        jLabelFileName.setText("Name:");

        jLabelFolderName.setText("Save in Folder: ");

        jTextFieldFolderName.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldFolderNameMouseClicked(evt);
            }
        });

        jButtonSave.setText("Save");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        jButtonCancel.setText("Cancel");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelButtonLayout = new javax.swing.GroupLayout(jPanelButton);
        jPanelButton.setLayout(jPanelButtonLayout);
        jPanelButtonLayout.setHorizontalGroup(
            jPanelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelButtonLayout.createSequentialGroup()
                .addGap(221, 221, 221)
                .addComponent(jButtonSave)
                .addGap(5, 5, 5)
                .addComponent(jButtonCancel))
        );

        jPanelButtonLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButtonCancel, jButtonSave});

        jPanelButtonLayout.setVerticalGroup(
            jPanelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelButtonLayout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jButtonSave))
            .addGroup(jPanelButtonLayout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jButtonCancel))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanelButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelFileName)
                            .addComponent(jLabelFolderName))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldFolderName, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE)
                            .addComponent(jTextFieldFileName, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabelFileName, jLabelFolderName});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jTextFieldFileName, jTextFieldFolderName});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelFileName)
                    .addComponent(jTextFieldFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldFolderName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelFolderName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldFileNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldFileNameActionPerformed
        file = new File(file.getParent()+File.separator+jTextFieldFileName.getText());
    }//GEN-LAST:event_jTextFieldFileNameActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        saveFile();
        dispose();
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jTextFieldFolderNameMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldFolderNameMouseClicked
        selectFolder();
    }//GEN-LAST:event_jTextFieldFolderNameMouseClicked

    /*
     * Init
     */
    private void initCustomComponents() {
        System.out.println(viewer.recording.getName());
        jTextFieldFileName.setText(viewer.recording.getName());
        jTextFieldFolderName.setText(viewer.recPath);
        file = new File(viewer.recPath+File.separator+jTextFieldFileName.getText());
    }
    
    /*
     * Select folder
     */
    private void selectFolder() {
        fc = new JFileChooser(jTextFieldFolderName.getText());
        fc.showOpenDialog(this);
        jTextFieldFolderName.setText(fc.getCurrentDirectory().getPath());
        jTextFieldFileName.setText(fc.getSelectedFile().getName());
        file = fc.getSelectedFile();
    }
    
    /*
     * Save
     */
    private void saveFile() {
        if(file.exists()) {
            if( !optionDialog("Do you want to overwrite the selected recording?")) return;
        }
        
        try {
            output = new FileOutputStream(file);
            Sequence.Builder sequence = Sequence.newBuilder();
            sequence.setName(file.getName());
            sequence.setLabel(viewer.getSequenceLabel());
            Frame.Builder frame; 
            for(int i=1, k = viewer.getStartIndex()-1; i <= viewer.getSelectionCount(); i++, k++) {
                frame = Frame.newBuilder();            
                frame.setNumber(i);
                frame.setSkeleton(viewer.sequence.getFrame(k).getSkeleton());
                frame.setFov(viewer.sequence.getFrame(k).getFov());
                sequence.addFrame(frame.build());
            }
            sequence.build().writeTo(output);
            output.close();
            System.out.println("File "+file.getName()+" saved.");
        } catch (IOException ex) {
            System.err.println("Error: file "+file.getName()+" not saved!");
            ex.printStackTrace();
        }
    }

    private boolean optionDialog(String msg) {
        JDialog.setDefaultLookAndFeelDecorated(true);
        int response = JOptionPane.showConfirmDialog(null, msg, "Confirm",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.YES_OPTION) {
            return true;
        } 
        return false;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName()); 
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SaveSequence.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SaveSequence().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JLabel jLabelFileName;
    private javax.swing.JLabel jLabelFolderName;
    private javax.swing.JPanel jPanelButton;
    private javax.swing.JTextField jTextFieldFileName;
    private javax.swing.JTextField jTextFieldFolderName;
    // End of variables declaration//GEN-END:variables
}
